<template>
	<view class="ectronic-signature">
		<canvas class="board-canvas" canvas-id="drawCanvas" disable-scroll="true" @touchstart="touchStart"
			@touchmove="touchMove" @touchend="touchEnd" style="width: 100%; height: 500rpx;"></canvas>
		<view class="btn">
			<div @click="clearDrawBoard" class="btnItem  color4">清空</div>
			<div  @click="saveImage"  class="btnItem">保存</div>
		</view>
	</view>
</template>


<script>
	import urlConfig from "@/request/urlConfig.js";
	export default {
		data() {
			return {
				curDrawArr: [],
				startX: 0,
				startY: 0,
				ctx: {},
				begin: false,
				bgColor: 'white', //背景色
				lineWidth: 4, //画笔宽度
				penMode: true, //打开画笔  开关
				currentTab: 1,
				currentIndex: 0,
				selectPointer: [], //所有选中的线
				cache: '',
				points: [],
				listOptin:[],
				src:""
			};
		},
		mounted() {
			console.log(11111111111);
			this.ctx = uni.createCanvasContext('drawCanvas', this); // 获取canvas上下文对象 vue的写法是先获取，之后通过.getContext("2d")来获取上下文
			this.cache = new Map(); // 缓存
			this.ctx.setLineWidth(this.lineWidth); // 设置画笔的粗细
		},

		methods: {
			// ctx.draw()绘制结果呈现在canvas
			// isReverse: 是否保留之前的像素
			draw(isReverse = false, cb) {
				this.ctx.draw(isReverse, () => {
					if (cb && typeof cb == 'function') {
						cb();
					}
				});
			},

			// 绘画 开始
			touchStart(e) {
				console.log('绘画开始', e.touches[0].x, e.touches[0].y);
				// customPrint('我能够进行绘制');
				if (this.penMode) {
					this.lineBegin(e.touches[0].x, e.touches[0].y);
					this.lineAddPoint(e.touches[0].x, e.touches[0].y);
					this.draw(true, ''); // 呈现画面
				}
				this.points.push([e.touches[0].x, e.touches[0].y]); // 存储绘制的点
				this.selectPointer.push([
					[e.touches[0].x, e.touches[0].y]
				]);
			},

			// 开始绘制线条
			lineBegin(x, y) {
				this.begin = true; // 作为一个标记代表开始绘画
				this.ctx.beginPath(); // 开始创建一个路径
				this.startX = x;
				this.startY = y;
				this.ctx.moveTo(this.startX, this.startY); // 将路径移动到画布中的指定点
				this.lineAddPoint(x, y); // 绘制线条中间添加
			},

			// 绘画 移动
			touchMove(e) {
				// console.log('绘画移动', e.touches[0].x, e.touches[0].y);
				this.listOptin.push(e.touches[0].y)

				if (this.begin) {
					if (this.penMode) {
						this.lineAddPoint(e.touches[0].x, e.touches[0].y);
						this.draw(true, '');
					}
					this.points.push([e.touches[0].x, e.touches[0].y]);
					this.selectPointer[this.selectPointer.length - 1].push([e.touches[0].x, e.touches[0].y]);
				}
			},

			// 绘制线条中间添加点
			lineAddPoint(x, y) {
				this.ctx.moveTo(this.startX, this.startY);
				this.ctx.lineTo(x, y); // 增加一个新的点，然后创建一条从上次指定点到目标点的线
				this.ctx.stroke(); // 画出当前路径的边框
				this.startX = x;
				this.startY = y;
			},

			// 绘画 结束
			touchEnd(e) {
				if (this.penMode) {
					// this.curDrawArr = [];
					this.points = [];
					this.lineEnd();
				}
			},

			// 绘制线条结束
			lineEnd() {
				this.ctx.closePath(); // 关闭一个路径，关闭路径会连接起点和终点
				this.begin = false;
			},

			// 检验画布是否为空
			isCanvasBlank(canvas) {
				const blank = document.createElement('canvas'); //系统获取一个空canvas对象
				console.log(blank);
				blank.width = canvas.width;
				blank.height = canvas.height;
				return canvas.toDataURL() == blank.toDataURL(); // .toDataURL()将canvas对象转换为base64位编码
			},

			// 保存 图片数据
			saveImage() {
				if(this.selectPointer.length<=0){
					uni.showToast({
						title: '请签字！！！',
						icon: 'none',
					});
					return false;
				}
				console.log(this.selectPointer,"selectPointer");
				const _this = this;
				uni.canvasToTempFilePath({
					canvasId: 'drawCanvas',
					success: (res) => {
						console.log('res ==>', res);
						let str = res.tempFilePath;
						const blob = this.parseBlob(str);
						this.src = blob
						uni.uploadFile({
							url: urlConfig.baseURL +'/sys/file/uploadFile',
							filePath: blob,
							name: "file",
							header: {
								'User-Token': uni.getStorageSync('token') || "",
							},
							success: resUpload => {
								console.log(JSON.parse(resUpload.data).datas.file_path, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
								let file_path = JSON.parse(resUpload.data).datas.file_path
								uni.showToast({
									title: '保存成功',
									icon: 'none',
								});
								this.$emit('comit',file_path)
							},
							fail:(err)=>{
								console.log(err,"err");
							}
						})
					},
				});
			
			},

			//清除
			clearDrawBoard() {
				this.ctx.draw();
				this.selectPointer = [];
			},
			parseBlob(str) {
				var arr = str.split(",");
				var mime = arr[0].match(/:(.*?);/)[1];
				var bstr = atob(arr[1]);
				var n = bstr.length;
				var u8arr = new Uint8Array(n);
				for (var i = 0; i < n; i++) {
					u8arr[i] = bstr.charCodeAt(i);
				}
				var url = URL || webkitURL;
				return url.createObjectURL(new Blob([u8arr], {
					type: mime
				}));
			},
		}
	}
</script>

<style lang="scss">
	.ectronic-signature {
		width: 100%;
	}

	.board-canvas {
		width: 100%;
		height: 500rpx;
		border: 1rpx solid #ccc;
		margin: 10rpx 0;
		border-radius: 4rpx;
	}

	.btn {
		display: flex;
		justify-content: space-around;
	}
	.btnItem{
		width: 180rpx;
		border-radius: 50rpx;
		background-color: #EAF1FE;
		color: #5588E0;
		height: 70rpx;
		text-align: center;
		line-height: 70rpx;
		font-weight: 500;
	}
	.color4{
		background-color: #ccc;
		color: #FFF;
	}
</style>